<template>
  <div>

    <div class="header-select">
      <el-input class="input" placeholder="请输入共享id" prefix-icon="el-icon-search" v-model="shareId" clearable></el-input>
      <el-input class="input" placeholder="请输入提取码" prefix-icon="el-icon-search" v-model="password" clearable></el-input>

      <el-cascader ref="cascaderData" class="select" :show-all-levels="true" v-model="folderId" :options="folders"
        :props="{checkStrictly: true }" @change="change"></el-cascader>

      <el-button class="btn" type="primary" round @click="search()">查询
        <i class="el-icon-search el-icon--right"></i>
      </el-button>
      <el-button class="btn" type="primary" round @click="save()">转存
        <i class="el-icon-plus el-icon--right"></i>
      </el-button>
      <el-button class="btn" type="primary" round @click="back()">返回上一级
        <i class="el-icon-back el-icon--right"></i>
      </el-button>

    </div>


    <!-- 表格 -->
    <div class="table">

      <el-table class="file_table" ref="fileTable" :data="fileData" style="width: auto"
        :show-header="folderData.length == 0">
        <el-table-column type="selection" />

        <el-table-column label="文件名" width="auto">
          <template slot-scope="scope">
            <div style="display: flex;">
              <i class="el-icon-document icon-table" v-if="scope.row.type=='DOCUMENT_FILE'"></i>
              <i class="el-icon-video-camera-solid icon-table" v-if="scope.row.type=='VIDEO_FILE'"></i>
              <i class="el-icon-collection icon-table" v-if="scope.row.type=='OTHER_FILE'"></i>

              <el-image class="icon-table" style="width: 50px; height: 50px" :src="http+scope.row.virtualPath"
                fit="fill" v-if="scope.row.type == 'IMAGE_FILE'">
              </el-image>

              <i v-if="scope.row.folderId != null" style="font-weight:bold;"
                class="el-icon-folder-opened icon-table"></i>

              <a v-if="scope.row.folderId != null" title="点击预览"
                :href="scope.row.virtualPath != ''?http + scope.row.virtualPath:'previewErr'" target="_blank"
                style="text-decoration: none;align-self: center;color: #000;">{{scope.row.fileName}}</a>
              <a v-else title="打开文件夹"
                style="text-decoration: none;align-self: center; cursor: pointer;font-weight:bold;"
                @click="folderPreview(scope.row)">{{scope.row.folderName}}</a>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="修改时间" width="150px">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.updateTime }}</span>
          </template>
        </el-table-column>


        <el-table-column prop="size" label="大小" width="100px"></el-table-column>

      </el-table>

    </div>

    <!-- 分页 -->
    <div class="page">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="pageSizes" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="请选择要保存到哪个文件夹" class="update_dialog" :visible.sync="dialog">

      <el-form status-icon label-width="100px" class="demo-ruleForm">
        <!-- 下拉框 -->
        <el-form-item label="文件夹：">
          <el-cascader ref="cascaderData" class="select" :show-all-levels="true" v-model="myFolderId"
            :options="myFolders" :props="{checkStrictly: true }"></el-cascader>
        </el-form-item>

        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="doSave()">提交</el-button>
          <el-button @click="cencel()">取消</el-button>
        </el-form-item>

      </el-form>

    </el-dialog>


  </div>
</template>

<script>
  import apiUrl from '@/api/url'
  import link from '@/api/Link'
  import router from "@/router"
  import sizeTostr from '@/util/FileSizeUtil'

  export default {
    name: 'ShareFolder',
    components: {

    },
    data () {
      return {
        http: apiUrl.baseUrl,
        pageSize: 5,
        pageSizes: [10, 15, 20, 30],
        currentPage: 1,
        total: 0,

        fileData: [],
        folderData: [],

        password: '',
        shareId: '',

        folders: [],
        folderId: [],

        dialog: false,
        myFolderId: [],
        myFolders: [],
      }
    },
    methods: {
      //初始化
      init () {

        let element = {
          shareId: this.shareId,
          password: this.password,
          folderId: this.folderId[this.folderId.length - 1]
        }
        link(apiUrl.baseUrl + '/sys/share/findShareByPage/v1', 'POST', JSON.stringify(element)).then(ok => {
          if (ok.data.code == 0) {
            this.total = ok.data.data.total
            this.fileData = []
            for (let i = 0; i < ok.data.data.childFolders.length; i++) {
              this.fileData.push(ok.data.data.childFolders[i])
            }
            for (let i = 0; i < ok.data.data.files.length; i++) {
              ok.data.data.files[i].size = sizeTostr(ok.data.data.files[i].size)
              this.fileData.push(ok.data.data.files[i])
            }
          } else {
            this.$message.error('数据请求失败：' + ok.data.msg)
          }
        })

      },
      //构建下拉框
      cascaderInit (data) {
        if (!data) {
          return
        }
        let folders = {
          value: data.folder.id,
          label: data.folder.folderName,
          children: []
        }

        data.childFolders.forEach(element => {
          folders.children.push(this.cascaderInit(element))
        });

        return folders;
      },
      //分页监控
      handleCurrentChange (val) {
        this.currentPage = val
        this.init()
      },
      //分页监控
      handleSizeChange (val) {
        this.pageSize = val;
        this.init()
      },
      //搜索按钮
      search () {
        let data = {
          shareId: this.shareId,
          password: this.password
        }
        link(apiUrl.baseUrl + '/sys/share/getShareFolderById/v1', 'POST', JSON.stringify(data)).then(ok => {
          if (ok.data.code == 0) {
            this.folderId = []
            this.folders = []
            this.folders.push(this.cascaderInit(ok.data.data))
            this.fileData = []
            this.fileData.push(ok.data.data.folder)
          } else {
            this.fileData = []
            this.folderData = []
            this.folders = []
            this.folderId = []
            this.$message.error('数据请求失败：' + ok.data.msg)
          }
        })




      },
      //文件夹部查看按钮
      folderPreview (row) {
        let folderId = JSON.parse(JSON.stringify(this.folderId))
        folderId.push(row.id)
        this.folderId = folderId
        this.init()
      },
      //文件部分查看按钮
      preview (row) {
        if (row.virtualPath) {
          window.open(apiUrl.baseUrl + row.virtualPath)
        } else {
          let page = this.$router.resolve({
            name: 'previewErr',
          })
          window.open(page.href, '_blank');
        }
      },
      //返回上一级
      back () {
        if (this.folderId.length <= 0) {
          this.$message({
            message: "当前已是根目录，不能返回上一级",
            type: "info",
          });
          return;
        }
        let folderId = JSON.parse(JSON.stringify(this.folderId))
        folderId.pop()
        this.folderId = folderId
        this.change()
      },
      //选择框监听
      change () {
        if (this.folderId.length <= 0) {
          this.search()
        } else {
          this.init()
        }
      },
      //转存按钮
      save () {
        this.dialog = true
        let user = JSON.parse(localStorage.getItem('user'))

        let data = {
          state: 0,
          id: user.rootId
        }
        //下拉框--获取数据
        link(apiUrl.baseUrl + '/sys/folder/findList/v2', 'POST', JSON.stringify(data), null).then((ok) => {
          this.myFolders = []
          this.myFolders.push(this.cascaderInit(ok.data.data))
        })
        let rootId = user.rootId
        this.myFolderId = []
        this.myFolderId.push(rootId)
        this.dialog = true
      },
      //保存提交
      doSave () {

        let fileIds = []
        let folderIds = []
        let fileSelection = this.$refs.fileTable.selection;


        for (let index = 0; index < fileSelection.length; index++) {
          const element = fileSelection[index];
          if (element.folderId != null) {
            fileIds.push(element.id)
          } else {
            folderIds.push(element.id)
          }
        }
        if (fileIds.length == 0 && folderIds.length == 0) {
          this.$message({
            message: "请选择文件",
            type: "warning",
          });
          return
        }
        let data = {
          folderId: this.myFolderId[this.myFolderId.length - 1],
          shareId: this.shareId,
          password: this.password,
          fileIds: fileIds,
          folderIds: folderIds
        }
        link(apiUrl.baseUrl + '/sys/share/saveShare/v1', 'POST', JSON.stringify(data)).then(ok => {
          if (ok.data.code == 0) {
            this.$message({
              message: "保存成功，请到文件夹查看",
              type: "success",
            });
            router.push("/folders");
          } else {
            this.$message({
              message: "保存失败：" + ok.data.msg,
              type: "error",
            });
          }
        })
      },
      //取消
      cencel () {
        this.dialog = false
      },
    },

    mounted () {

    },
    watch: {

    }

  }
</script>

<style scoped>
  .table {
    margin: 10px;
    /* width: 90%;   */
  }

  .header-select {
    margin: 10px;
    display: flex;
  }

  .btn {
    margin-left: 10px;
  }

  .input {
    width: 220px;
    margin-right: 10px;
  }

  .table {
    width: 90%;
  }

  .icon-table {
    margin-right: 10px;
    display: flex;
    align-self: center;
  }
</style>